/*扩展以时间作为滚动切换的日志落地模块
   以时间进行滚动,实际上是以时间段进行滚动
   time(nullptr) % gap = ?; 第几个时间段
   时间段一致，继续写入，不同切换文件
*/

#include "../log/log.h"

enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public log::LogSink
{
public:
    RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = _gap_size == 1 ? log::util::Date::getTime() : log::util::Date::getTime() % _gap_size;
        std::string filename = createNewFile();
        log::util::File::createDirectory(log::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void log(const char *data, size_t len)
    {
        time_t cur = log::util::Date::getTime();
        if ((cur % _cur_gap) != _cur_gap)
        {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_gap = _gap_size == 1 ? log::util::Date::getTime() : log::util::Date::getTime() % _gap_size;
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile()
    {
        // 获取当前时间，形成文件名
        time_t time = log::util::Date::getTime();
        struct tm tm;
        localtime_r(&time, &tm);

        std::stringstream filename;
        filename << _basename;
        filename << tm.tm_year + 1900;
        filename << tm.tm_mon + 1;
        filename << tm.tm_mday;
        filename << tm.tm_hour;
        filename << tm.tm_min;
        filename << tm.tm_sec;
        filename << ".log";

        return filename.str();
    }

private:
    // 通过基础文件名 + 扩展文件名（以时间生成）组成一个实际的当前输出文件名
    std::string _basename; // ./log/base-   -->  ./log/base-2023824
    std::ofstream _ofs;
    size_t _cur_gap;  // 当前是第几个时间段
    size_t _gap_size; // 时间段大小
};

int main()
{
    std::unique_ptr<log::LoggerBuilder> builder(new log::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(log::LogLevel::value::DEBUG);
    builder->buildLoggerType(log::LoggerType::LOGGER_ASYNC);//日志器类型
    //builder->buildEnableUnsafeAsync();//异步日志器设置为不安全模式
    builder->buildFormatter("[%c]%m%n");
    builder->buildSink<RollByTimeSink>("./logfile/async.log",TimeGap::GAP_SECOND);
    log::Logger::ptr logger = builder->build();
    size_t cur = log::util::Date::getTime();
    while(log::util::Date::getTime() < cur +5)
    {
        logger->info("测试日志消息");
        usleep(1000);
    }
}